package com.groupbuying.payconsumer.mq;

import com.aliyun.openservices.ons.api.Message;
import com.aliyun.openservices.ons.api.Producer;
import com.aliyun.openservices.shade.com.alibaba.fastjson.JSON;
import com.aliyun.openservices.shade.com.alibaba.fastjson.serializer.SerializerFeature;
import com.groupbuying.payconsumer.connector.OrderFeign;
import com.groupbuying.payconsumer.connector.SysconfigFeign;
import com.groupbuying.payconsumer.connector.YsPayFeign;
import com.groupbuying.payconsumer.constants.CommonConstants;
import com.groupbuying.payconsumer.constants.PayInfoEnumConstants;
import com.groupbuying.payconsumer.domain.PayInfoDO;
import com.groupbuying.payconsumer.domain.PayOrderRelDO;
import com.groupbuying.payconsumer.service.PayInfoService;
import com.groupbuying.payconsumer.service.PayOrderRelService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 银盛支付主动查询逻辑处理类
 * @Author Vincentxin
 * @Date 2019-06-28
 */
@Component
public class PayOrderStateConfirm {
    public static final Logger LOGGER = LoggerFactory.getLogger(PayOrderStateConfirm.class);
    @Autowired
    private PayInfoService payInfoService;

    @Autowired
    private PayOrderRelService payOrderRelService;

    @Autowired
    private YsPayFeign ysPayFeign;

    @Autowired
    private Producer producer;

    @Autowired
    private OrderFeign orderFeign;

    @Autowired
    private SysconfigFeign sysconfigFeign;

    public boolean dealResult(Map<String,Object> resultParam) {
        String dealNo = resultParam.get("key") == null ? "" : resultParam.get("key").toString();
        if (StringUtils.isEmpty(dealNo)){
            LOGGER.error("第三方交易单号不存在");
            return false;
        }
        LOGGER.info("=====银盛支付，支付结果主动查询开始 第三方交易单号：{}",dealNo);
        //查询订单支付是否已经完成
        try {
            PayOrderRelDO payOrderRelDO = payOrderRelService.getByOutTradeNo(dealNo);
            PayInfoDO payInfoDO = payInfoService.get(payOrderRelDO.getId());
            //支付单已经支付完成
            if (PayInfoEnumConstants.ENUM_PAYSTATE_SUCPAY.equals(payInfoDO.getPayState())) {
                LOGGER.info("支付单已经完成:{}" ,payInfoDO.getId());
                return true;
            }
            //支付单状态不是未支付
            if (!PayInfoEnumConstants.ENUM_PAYSTATE_UNPAY.equals(payInfoDO.getPayState())) {
                LOGGER.info("支付单已经进行了其他操作:{}" ,payInfoDO.getId());
                return true;
            }
            Map<String, String> param = new HashMap<>();
            param.put("outTradeNo", dealNo);

            Map<String, Object> result = ysPayFeign.ysPayQuery(param);
            //如果可以查询不到第三方有此订单
            if (result.isEmpty()) {
                LOGGER.error("第三方支付订单outTradeNo:{},支付单号:{},第三方无此订单" ,dealNo , payInfoDO.getId());
                return true;
            }
            //如果查询结果不是交易成功
            if (!"TRADE_SUCCESS".equals(result.get("trade_status").toString())) {
                LOGGER.info("第三方支付订单outTradeNo：" + dealNo + "查询结果为" + result.get("trade_status").toString());
                return false;
            }
            payInfoDO.setPayState(PayInfoEnumConstants.ENUM_PAYSTATE_SUCPAY);
            payInfoDO.setGmtModified(new Date());
            payInfoService.update(payInfoDO);
            LOGGER.info("支付单号" + payInfoDO.getId() + "第三方交易单号：" + dealNo + "同步修改支付单状态执行完成");
            //获取订单信息
            Map orderMap = orderFeign.getOrderForPay(payOrderRelDO.getOrderId());
            //订单是否属于够样优店
            boolean curNotify = orderMap.get("orderId").toString().substring(4, 7).equals("000");
            //商户优惠规则
            if (curNotify) {
                Map ruleMap = new HashMap();
                ruleMap.put("ruleId", orderMap.get("opxRuleId"));
                ruleMap.put("delFlag", CommonConstants.COMMON_FLAG_UNDEL);
                Map rulesMap = sysconfigFeign.getStoreOpexRule(ruleMap);
                orderMap.putAll(rulesMap);
            }

            //设置订单中心消息传递消息体
            Map<String, Object> orderParam = new HashMap<>();
            orderParam.put("orderId", orderMap.get("orderId"));
            //设置积分中心消息传递消息体
            Map<String, Object> currencyParam = new HashMap<>();
            if (curNotify) {
                currencyParam.put("payId", payInfoDO.getId());
                currencyParam.put("customerId", orderMap.get("customerId"));
                currencyParam.put("consumptionAmount", orderMap.get("orderPrice"));
                currencyParam.put("backCurrencyRatio", orderMap.get("backCurrencyRatio"));
            }
            //设置分账中心消息传递内容
            Map<String, Object> settleParam = new HashMap<>();
            settleParam.put("orderId", orderMap.get("orderId"));
            settleParam.put("outTradeNo", payOrderRelDO.getOutTradeNo());
            settleParam.put("ruleId", orderMap.get("opxRuleId"));
            settleParam.put("totalAmount", payInfoDO.getPayMoney());
            //收银台ID
            settleParam.put("counterId", orderMap.get("counterId"));
            //用户ID
            settleParam.put("customerId", orderMap.get("customerId"));
            //
            //支付分账
            settleParam.put("settleType", "0");
            settleParam.put("payType", payInfoDO.getPayType());
            settleParam.put("payChannel", payInfoDO.getPayChannel());

            try {
                //订单中心
                Message orderMessage = new Message(PayMQConfig.ORDER_TOPIC, PayMQConfig.ORDER_TAG_PAY,
                        JSON.toJSONString(orderParam, SerializerFeature.DisableCircularReferenceDetect).getBytes());
                producer.send(orderMessage);
                LOGGER.info("支付单号" + payInfoDO.getId() + "第三方交易单号：" + dealNo + "同步发送订单中心执行完成");
            } catch (Exception e) {
                e.printStackTrace();
                //发送不成功的话，稍后重试

            }
            if (curNotify) {
                try {
                    //积分中心
                    Message currencyMessage = new Message(PayMQConfig.CURRENCY_TOPIC, PayMQConfig.CURRENCY_TAG_ADD,
                            JSON.toJSONString(currencyParam, SerializerFeature.DisableCircularReferenceDetect).getBytes());
                    producer.send(currencyMessage);
                    LOGGER.info("支付单号" + payInfoDO.getId() + "第三方交易单号：" + dealNo + "同步发送积分中心执行完成");
                } catch (Exception e) {
                    e.printStackTrace();
                    //发送不成功的话，稍后重试
                }
            }
            try {
                //分账中心
                Message settleMessage = new Message(PayMQConfig.SETTLE_TOPIC, PayMQConfig.SETTLE_TAG_SPLIT,
                        JSON.toJSONString(settleParam, SerializerFeature.DisableCircularReferenceDetect).getBytes());
                producer.send(settleMessage);
                LOGGER.info("支付单号" + payInfoDO.getId() + "第三方交易单号：" + dealNo + "同步发送分账中心执行完成");
            } catch (Exception e) {
//                        LOGGER.error("订单号：" + payYsResultDO.getId() + "，银盛内部单号：" + payYsResultDO.getTradeNo() + "，发送分账中心失败");
                e.printStackTrace();
                //发送不成功的话，稍后重试
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return true;
    }
}
